import { useEffect, useState } from 'react';
import { prorListApi } from '@/api/pro';
import { Table, Image, Switch, Button } from 'antd';
// 直接导出文件
import ExportJsonExcel from 'js-export-excel';

import './list.less';

const Index = () => {
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);
  const [count, setCount] = useState(1);
  const [limitNum, setLimitNum] = useState(10);

  const [options, setOptions] = useState([]);

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
    },
    {
      title: '产品名称',
      dataIndex: 'proname',
      width: 200,
    },
    {
      title: '产品图片',
      // dataIndex: 'img1',
      render(text: string, record: any) {
        return <Image src={record.img1}></Image>;
      },
      width: 150,
    },
    {
      title: '产品分类',
      dataIndex: 'category',
    },
    {
      title: '产品品牌',
      dataIndex: 'brand',
    },
    {
      title: '价格',
      dataIndex: 'originprice',
    },
    {
      title: '折扣',
      dataIndex: 'discount',
    },
    {
      title: '库存',
      dataIndex: 'stock',
    },
    {
      title: '是否售卖',
      dataIndex: 'issale',
      render(text: number) {
        return (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={text === 1}
          />
        );
      },
    },
  ];

  useEffect(() => {
    prorListApi({
      count: count,
      limitNum: limitNum,
    }).then((res) => {
      if (res) {
        const result = res.data.map((item: any, index: number) => ({
          ...item,
          key: index + 1,
        }));
        setDataSource(result);
      }
    });
  }, []);

  const exportFile = () => {
    var option: any = {};

    option.fileName = '商品列表';

    option.datas = [
      {
        sheetData: dataSource,
        sheetName: 'sheet',
        sheetFilter: ['proname', 'category', 'img1'],
        sheetHeader: ['产品名称', '产品分类', '商品图片'],
        columnWidths: [20, 20],
      },
    ];

    var toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  };

  return (
    <div>
      <Button onClick={exportFile}>导出</Button>
      <Table dataSource={dataSource} columns={columns} pagination={false} />
    </div>
  );
};

export default Index;
